package com.wg.dao;

import com.wg.entity.User;
import com.wg.entity.WGInfo;
import com.wg.model.DBOperator;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class WGInfoDao {
    private List<WGInfo> wgInfos;

    private WGInfoDao(){
        wgInfos = (ArrayList) findAll();
    }

    private static WGInfoDao wgInfoDao;

    public static WGInfoDao getInstance(){
        return WGInfoDao.SingletonHander.singleton;
    }

    private static class SingletonHander{
        private static final WGInfoDao singleton = new WGInfoDao();
    }


    /**
     * 功能描述:查询所有数据
     */
    public List<WGInfo> findAll() {
        List<WGInfo> ret = new ArrayList<>();
        String pathName = ".\\src\\main\\resources\\saves\\WGInfo.data";

        try(FileReader reader = new FileReader(pathName);
            BufferedReader br = new BufferedReader(reader)){
            String line;
//           按行读取数据
            while ((line = br.readLine()) != null && line.isEmpty() == false){
                WGInfo wg = new WGInfo();
                wg.deserialize(line);
                ret.add(wg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }
    /**
     * 功能描述: 由wgId查询数据
     */
    public WGInfo findById(Integer wgId) {
        List<WGInfo> ret = wgInfos.stream().filter(wg -> wg.id == wgId).collect(Collectors.toList());
        return ret.get(0);
    }
    /**
     * 功能描述: 添加数据
     */
    public boolean addUser(WGInfo wgInfo) {
        wgInfos.add(wgInfo);
        return update();
    }

    /**
     * 功能描述: 由userId删除数据
     */
    public boolean deleteById(Integer wgId) {
        wgInfos.removeIf(wg -> wg.id == wgId);
        return update();
    }
    /**
     * 功能描述:由userId修改数据
     */
    public boolean updateById(WGInfo wgInfo) {
        for (WGInfo data: wgInfos) {
            if(data.id == wgInfo.id){
                data = wgInfo;
            }
        }
        return update();
    }


    /**
     * 功能描述:把数据更新到数据库
     */
    public boolean update() {
        String pathName = ".\\src\\main\\resources\\saves\\WGInfo.data";

        try {
            File writeName = new File(pathName);
            writeName.createNewFile();
            try (FileWriter writer = new FileWriter(writeName, true);
                 BufferedWriter out = new BufferedWriter(writer)){
                for (WGInfo data : wgInfos) {
                    out.write(data.serialize());
                    out.newLine();   // 换行
                }
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
